package features.advance.demo;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * @author LIN
 * @date 2022-04-09 16:21
 */
public class ClipboardDemo {

    public static void main(String[] args) {
        try {
            Image imageFromClipboard = getImageFromClipboard();
            if(imageFromClipboard!=null){
                ImageViewer imageViewer = new ImageViewer(imageFromClipboard);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Image getImageFromClipboard() throws Exception {

        Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard();

        Transferable cc = sysc.getContents(null);

        if (cc == null) {
            return null;

        } else if (cc.isDataFlavorSupported(DataFlavor.imageFlavor)) {
            return (Image) cc.getTransferData(DataFlavor.imageFlavor);
        }
        return null;

    }
}

/**
 *  用于显示图形的窗口
 */
class ImageViewer extends Frame{
    private final Image image;

    public ImageViewer(Image image){
        this.image = image;
        MediaTracker mediaTracker = new MediaTracker(this);
        mediaTracker.addImage(image,0);
        try{
            mediaTracker.waitForID(0);
        }catch(Exception e){
            e.printStackTrace();
            System.exit(1);
        }

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        // 窗口适应图像大小
        setSize(image.getWidth(null),image.getHeight(null));

        // 窗口标题
        setTitle("Viewing Image from Clipboard");
        setVisible(true);
    }

    @Override
    public void paint(Graphics graphics) {
        graphics.drawImage(image, 0, 0, null);

    }

    /**
     * 用于读取图像文件并生成Image对象
     */
    public static Image getImageFromFile(String fileName) {

        Toolkit toolkit = Toolkit.getDefaultToolkit();

        Image image = toolkit.getImage(fileName);

        return image;
    }



}
